/*
 * MIT License
 *
 * Copyright (c) 2024-2025 milkpotatoes
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import { UniversalKVStroe } from 'uni_kv_store';

const innerMap: WeakMap<Headers, UniversalKVStroe<string>> = new WeakMap();

export class Headers {
    constructor(init?: { [key: string]: string }) {
        innerMap.set(this, new UniversalKVStroe<string>())
        if (!init) {
            return;
        }
        for (let [k, v] of Object.entries(init)) {
            innerMap.get(this)!.data.push([k, String(v)]);
        }
    };
    append(name: string, value: string) {
        return innerMap.get(this)!.append(name, value);
    };
    delete(name: string) {
        return innerMap.get(this)!.delete(name);
    };
    entries() {
        return innerMap.get(this)!.entries();
    };
    forEach(callback: ForEachCallback<Headers, string>, thisArg?: Object): void {
        return innerMap.get(this)!.forEach(callback, this, thisArg);
    };
    get(name: string): string | undefined {
        return innerMap.get(this)!.get(name) ?? undefined;
    };
    getSetCookie(): string[] {
        return innerMap.get(this)!.getAll('Set-Cookie');
    };
    has(name: string): boolean {
        return innerMap.get(this)!.has(name);
    };
    keys() {
        return innerMap.get(this)!.keys();
    }
    set(name: string, value: string): void {
        return innerMap.get(this)!.set(name, value);
    }
    values() {
        return innerMap.get(this)!.values();
    }
}

Object.defineProperty(globalThis, 'Headers', {
    value: Headers,
    enumerable: false,
    writable: true,
    configurable: true,
});